package com.ellecity06.common.helper

import android.R.attr.tag
import android.annotation.SuppressLint
import android.media.MediaRecorder
import android.os.Environment
import android.util.Log
import java.text.SimpleDateFormat
import java.util.*
import android.os.Handler
import com.ellecity06.common.utils.FileUtil
import com.ellecity06.common.utils.appContext
import com.ellecity06.common.utils.logD
import com.huawei.hms.feature.dynamic.b.D
import java.io.File
import kotlin.math.abs
import kotlin.math.log10


/**
 * @author zavier
 * @time 2025/3/13 19:29
 * @des 录音工具
 */

class SoundRecorder constructor(private val rootPath: String = "", private val onDecibelUpdate: (Double) -> Unit) {

    private val tag = SoundRecorder::class.java.name

    var mRecorder: MediaRecorder? = null

    var isRecorder: Boolean = false

    var fileName: String = ""

    private val voiceBase = 1

    // 间隔取样时间
    private val voiceSpace: Long = 100

    private var voiceRecorder: VoiceRecorder? = null

    /**
     * 录音操作
     *
     */
    @SuppressLint("MissingPermission")
    fun startRecording(): Boolean {
        // 设置录音状态
        isRecorder = true
        // 创建媒体对象
        mRecorder = MediaRecorder()
        // 设定采集来源
        mRecorder!!.setAudioSource(MediaRecorder.AudioSource.MIC)
        // 设定输出格式
        mRecorder!!.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
        // 设定文件路径
        mRecorder!!.setOutputFile(newFileName(rootPath))
        // 设定编码
        mRecorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)

        try {
            // 准备
            mRecorder!!.prepare()
            // 开始录音
            mRecorder!!.start()
            voiceRecorder = VoiceRecorder(onDecibelUpdate)
            voiceRecorder?.startRecording()
//            updateMicVoiceStatus()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(tag, "prepare() failed")
            throw e
        }
        return isRecorder
    }

    fun stopRecording(): String {
        if (isRecorder) {
            // 停止录音
            mRecorder!!.stop()
            // 清除
            mRecorder!!.release()
            // 置空
            mRecorder = null
            // 设定录音状态
            isRecorder = false
        }
        voiceRecorder?.stopRecording()
        return fileName
    }

    /**
     * 创建录音文件
     *
     */
    @SuppressLint("SimpleDateFormat")
    private fun newFileName(rootPath: String = ""): String {

        fileName = "${appContext.externalCacheDir?.absolutePath}/aud_${System.currentTimeMillis()}.m4a"
        return fileName
    }

}